package com.jsnkj.basic.util

import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.view.animation.DecelerateInterpolator
import com.jsnkj.basic.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.Locale


object MediaUtil {

    /**
     * 将图片信息存入相册数据库
     *
     * @param path     视频路径
     * @param duration 视频持续时间
     * @param width    视频宽度
     * @param height   视频高度
     */
    fun insertToImageGallery(context: Context, path: String) {
        val videoValues = ContentValues()
        videoValues.put(MediaStore.Images.Media.TITLE, "未定义")
        videoValues.put(MediaStore.Images.Media.MIME_TYPE, "image/png")
        videoValues.put(MediaStore.Images.Media.DATA, path)
        videoValues.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis().toString())
        videoValues.put(MediaStore.Images.Media.DESCRIPTION, context.getString(R.string.app_name))
        context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, videoValues)
    }


    fun savePuzzleBitmap(
        context: Context,
        bitmap: Bitmap,
        savePath: String,
        result: (state: Boolean, photoPath: String) -> Unit
    ) {
        val name = "puzzle_${System.currentTimeMillis()}.jpeg"

        if (bitmap2PicturesFolder(context, bitmap, savePath, name)) {
            val photoFile =
                "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)}${File.separator}${savePath}${File.separator}$name"

            result.invoke(true, photoFile)
        } else {
            result.invoke(false, "")
        }
    }

    /**
     * 保存照片到【共享存储空间DICM/】下
     *
     * 【Android 10以下】使用Java I/O方式将图片保存到指定文件夹，保存成功后，系统相册不会显示该图片，需手动通知相册刷新
     * 【Android 10及以上】使用MediaStore的方式将图片保存到指定文件夹，保存成功后，系统相册会显示该图片
     *
     * @param context 上下文
     * @param bitmap 图片
     * @param relativePath 从Pictures/开始的相对路径，eg：A/B，表示存储在SDCard根目录Pictures/A/B/目录下
     * @param name 文件名称  aa.png  aa,jpg
     * @return
     */
    private fun bitmap2PicturesFolder(
        context: Context,
        bitmap: Bitmap,
        relativePath: String,
        name: String
    ): Boolean {
        var result = false
        var mimeType = "image/jpeg"
        if (name.lowercase(Locale.getDefault()) == "png") {
            mimeType = "image/png"
        }

        if (Build.VERSION_CODES.Q > Build.VERSION.SDK_INT) {// Android 10以下
            val path =
                "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)}${File.separator}$relativePath${File.separator}"

            result = bitmap2File(bitmap, path, name)

            // 扫描新增加的图片到相册
            MediaScannerConnection.scanFile(
                context, arrayOf("${path}$name"), arrayOf(mimeType)
            ) { path1, uri ->

                //Log.d("保存照片", "path = $path1, uri = $uri")
            }
        } else {// Android 10及以上
            val values = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, name)
                put(MediaStore.Images.Media.MIME_TYPE, mimeType)
                put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_DCIM}${File.separator}$relativePath${File.separator}")
            }
            try {
                val uri = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                val out = context.contentResolver.openOutputStream(uri!!)
                if ("image/png" == mimeType) {
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
                } else {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)
                }
                out?.flush()
                out?.close()
                result = true
            } catch (e: IOException) {
                result = false
                e.printStackTrace()
            }
        }
        return result
    }


    /**
     * 保存Bitmap到文件
     * @param bitmap 图片数据
     * @param path 文件路径
     * @param name 文件名称
     * @return
     */
    private fun bitmap2File(bitmap: Bitmap, path: String, name: String): Boolean {
        var result = false

        // 检查路径是否存在，不存在创建之
        val file = File(path)
        if (!file.exists()) {
            file.mkdirs()
        }

        // 文件已存在，删除之
        val imageFile = File(file, name)
        if (imageFile.exists()) {
            imageFile.delete()
        }

        var format = Bitmap.CompressFormat.JPEG
        if (name.toLowerCase(Locale.getDefault()).endsWith("png")) {
            format = Bitmap.CompressFormat.PNG
        }

        try {
            imageFile.createNewFile()
            val fos = FileOutputStream(imageFile)
            bitmap.compress(format, 100, fos)
            fos.flush()
            fos.close()
            result = true
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return result
    }


    /**
     * 保存控件的能展示的内容，例如：webview的每一页
     */
    fun getViewBitmap(v: View?): Bitmap? {
        if (null == v) {
            return null
        }
        v.isDrawingCacheEnabled = true
        v.buildDrawingCache()
        v.measure(
            View.MeasureSpec.makeMeasureSpec(v.width, View.MeasureSpec.EXACTLY),
            View.MeasureSpec.makeMeasureSpec(v.height, View.MeasureSpec.EXACTLY)
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            v.layout(
                v.x.toInt(),
                v.y.toInt(),
                v.x.toInt() + v.measuredWidth,
                v.y.toInt() + v.measuredHeight
            )
        }
        val bitmap: Bitmap = Bitmap.createBitmap(
            v.drawingCache,
            0,
            0,
            v.measuredWidth,
            v.measuredHeight
        )
        v.isDrawingCacheEnabled = false
        v.destroyDrawingCache()
        return bitmap
    }


    public fun heartBeat(view: View) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            val scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f, 0.8f, 1.0f)
            val scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f, 0.8f, 1.0f)
            val anim = ObjectAnimator.ofPropertyValuesHolder(view, scaleX, scaleY)
            anim.duration = 1000
            anim.repeatCount = -1
            anim.interpolator = DecelerateInterpolator()
            anim.startDelay = 100
            anim.start()
        }
    }

}